<template>
    <div class="upload-pane">
        <el-upload
            action="jimu"
            :auto-upload="true"
            :show-file-list="false"
            :http-request="getImage"
            accept=".png,.jpeg,.jpg"
            drag
        >
            <div class="image-upload">
                <i class="el-icon-upload" v-if="!innerImage"></i>
                <template v-else>
                    <div class="inner-image">
                        <img :src="innerImage">
                    </div>
                    <el-button @click.stop="removeImage" class="remove-btn">
                        移除
                    </el-button>
                </template>
                <div class="el-upload__text">
                    将图片文件拖到此处，或<em>点击导入</em>
                </div>
                <div class="el-upload__tip" slot="tip">
                    只能上传jpg/png文件
                </div>
            </div>
        </el-upload>
    </div>
</template>

<script lang="ts">
import { Options, Vue } from 'vue-property-decorator';
import { ElButton, ElUpload } from 'element-plus';
// eslint-disable-next-line import/no-unresolved
import { ElUploadRequestOptions } from 'element-plus/lib/el-upload/src/upload.type';

@Options({
  components: {
    ElButton,
    ElUpload,
  },
})
export default class ImgUpload extends Vue {
    innerImage = '';

    getImage(params: ElUploadRequestOptions) {
      const { file } = params;
      const fs = new FileReader();
      fs.readAsDataURL(file);
      fs.onload = (e) => {
        this.innerImage = e.target?.result as string;
        this.$emit('getImage', this.innerImage);
      };
    }

    removeImage() {
      this.innerImage = '';
      this.$emit('getImage', this.innerImage);
    }
}
</script>

<style lang='less' scoped>
.inner-image{
    display: inline-block;
    margin-top: 30px;
    width: 67px;
    height: 67px;
    overflow: hidden;
    img {
        width: 67px;
        height: auto;
    }
}

:deep(.el-upload) {
    position: relative;
    width: 100%;
    height: 100%;
    .el-upload-dragger {
        width: 100%;
    }
    .remove-btn{
        position: absolute;
        right: 20px;
        top: 20px;
    }
}

.image-upload {
    .el-upload__text, .el-upload__tip {
        line-height: 20px;
    }
}
</style>
